package com.it.Controller;

import com.it.Service.LoginService;
import com.it.pojo.Result;
import com.it.pojo.User;
import com.it.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
@CrossOrigin(origins = "*") // 解决跨域问题，允许所有来源访问，实际中可配置具体域名
@RestController
public class LoginController {
    @Autowired
    private LoginService loginService;

    @PostMapping("/login")
    public Result login(@RequestBody User user){
        User u = loginService.login(user);
        //登陆成功，生成令牌，下发令牌
        if(u != null){
            if(u.getUStatus()==0){
                return Result.error("账号无效");
            }
            Map<String,Object> claims = new HashMap<>();
            claims.put("username",user.getUsername());
            claims.put("password",user.getPassword());
            String jwt = JwtUtils.generateJwt(claims);
            return Result.success(jwt);
        }
        //登录失败，返回错误信息
        return Result.error("用户名或密码错误");
    }

    @PutMapping("/user")
    public Result updateUser(@RequestBody User user){
        loginService.updateUser(user);
        return Result.success();
    }
}
